package com.ljx.recruitment.common.datapatch;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MainDataPatch implements ApplicationRunner {

    @Autowired
    private DataPatchService dataPatchService;

    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) {
        log.info("datapatch start");
        for (DataPatchStrategy dataPatchStrategy : getList()) {
            String name = dataPatchStrategy.getName();
            String version = dataPatchStrategy.getVersion();
            DataPatch dataPatch = dataPatchService.getByName(name);
            if (Objects.nonNull(dataPatch) && dataPatch.getVersion().equals(version)) {
                continue;
            }
            log.info("datapatch:[" + name + "-" + version + "] execute");
            dataPatchStrategy.run();
            if (Objects.isNull(dataPatch)) {
                dataPatch = new DataPatch(name, version);
            } else {
                dataPatch.setVersion(version);
            }
            dataPatchService.saveOrUpdate(dataPatch);
            log.info("datapatch:[" + name + "-" + version + "] end");
        }
        log.info("datapatch end");
    }

    private List<DataPatchStrategy> getList() {
        Map<String, DataPatchStrategy> beansOfType = applicationContext.getBeansOfType(DataPatchStrategy.class);
        return beansOfType.keySet().stream().map(beansOfType::get).sorted(new Comparator<DataPatchStrategy>() {
            @Override
            public int compare(DataPatchStrategy o1, DataPatchStrategy o2) {
                return o1.getSort() - o2.getSort();
            }
        }).collect(Collectors.toList());
    }
}
